import { defineComponent } from 'vue';
import { getJournal } from '@/api/home';
import {
  ElAvatar,
  ElDialog,
  ElDropdown,
  ElDropdownItem,
  ElDropdownMenu,
  ElIcon,
  ElImage
} from 'element-plus';
import { RollingText } from 'vant';
import { ArrowRight } from '@element-plus/icons-vue';
import { websiteLink, newsLink, dynamicLink } from '../../../Enum';
import './index.less';
import '../../../style/index.less';

import ItemTable from '../MyKpi/ItemTable';
import GroupItemTable from '../GroupKpi/ItemTable';
import HTip from '../../common/HTip';
import { generateAvatarByName } from '@/utils';
import MonthItem from "@/views/components/pc/MonthIndicator/ItemTable"

export default defineComponent({
  name: 'Synthesis',
  props: ['userInfo'],
  setup(props) {
    const monthItem = ref()
    const { VITE_STATIC_URL } = import.meta.env;
    const itemTableRef = ref();
    const groupItemTableRef = ref();
    const performanceId = ref();

    const dialogVisible = ref(false);
    const tableData = ref([]);
    const store = useStore();
    const dingdingInfo = computed(() => store.state.dingdingInfo || {});

    const pageable = ref({
      page: 1,
      pageSize: 15,
      total: 0
    }) as AnyObject;
    const router = useRouter();
    const data = ref({}) as AnyObject;

    const websiteSlots = {
      dropdown: () => (
        <ElDropdownMenu>
          {websiteLink.map((_item, _index) => (
            <ElDropdownItem>
              <a href={_item.link} target="_blank">
                {_item.name}
              </a>
            </ElDropdownItem>
          ))}
        </ElDropdownMenu>
      )
    };
    const newsSlots = {
      dropdown: () => (
        <ElDropdownMenu>
          {newsLink.map((_item, _index) => (
            <ElDropdownItem>
              <a href={_item.link} target="_blank">
                {_item.name}
              </a>
            </ElDropdownItem>
          ))}
        </ElDropdownMenu>
      )
    };
    const dynamicSlots = {
      dropdown: () => (
        <ElDropdownMenu>
          {dynamicLink.map((_item, _index) => (
            <ElDropdownItem>
              <a href={_item.link} target="_blank">
                {_item.name}
              </a>
            </ElDropdownItem>
          ))}
        </ElDropdownMenu>
      )
    };

    const detailTitle = () => {
      const date = new Date();
      let year = date.getFullYear();
      let month = (date.getMonth() + 1) as any;
      props.userInfo.column?.includes('1') && (month -= 1);
      year = month == 0 ? year - 1 : year;
      month = ('' + month).padStart(2, '0');
      return year + '-' + month;
    };
    const getJournalList = () => {
      dialogVisible.value = true;
    };
    const viewPerformanceDetail = (id: number) => {
      performanceId.value = id;
      itemTableRef.value.dialogVisible = true;
    };
    const rollText = (text: string, type: string) => {
      if (text) {
        const { month_rate, organize_rate, mysale_rate, score_rate } =
          dingdingInfo.value;
        const obj = {
          month_rate: {
            start: month_rate,
            compareStart: props.userInfo.sale_data?.month_rate || '-'
          },
          organize_rate: {
            start: organize_rate,
            compareStart: props.userInfo.organize_rate || '-'
          },
          score_rate: {
            start: score_rate,
            compareStart: props.userInfo.score_rate || '-'
          },
          mysale_rate: {
            start: mysale_rate,
            compareStart: props.userInfo.mysale_rate || '-'
          }
        } as AnyObject;
        if (obj[type].start != obj[type].compareStart) {
          setTimeout(
            () =>
              store.commit('storeDingdingInfo', {
                [type]: obj[type].compareStart
              }),
            1000
          );
          return (
            <RollingText
              text-list={[obj[type].start || "", obj[type].compareStart]}
              duration={1.3}
            />
          );
        } else {
          return (
            <RollingText
              autoStart={false}
              text-list={[obj[type].start || "", obj[type].start]}
              duration={1.3}
            />
          );
        }
      } else {
        return <p>-</p>;
      }
    };

    function getProductCase() {
      getJournal({
        page: pageable.value.page,
        pageSize: pageable.value.pageSize
      }).then((res) => {
        tableData.value = res.data.list;
        pageable.value.total = res.data.total;
      });
    }

    return () => (
      <>
        <div class="synthesis flex-between">
          <div class="left flex-start">
            <div class="personal flex-start">
              <ElAvatar
                src={
                  props.userInfo.avatar ||
                  generateAvatarByName(props.userInfo.name)
                }
              />
              <div>
                <div class="name text-truncate">Hi, {props.userInfo.name}</div>
                <div
                  class="detail hover-color flex-start"
                  onClick={() => router.push('/profile')}
                >
                  <span>个人资料</span>
                  <ElIcon>
                    <ArrowRight />
                  </ElIcon>
                </div>
              </div>
            </div>
            <div class="other flex-start">
              <div class="other_item">
                <ElDropdown v-slots={websiteSlots}>
                  <div>
                    <ElImage
                      src={`${VITE_STATIC_URL}/tcpl/p_website.png`}
                    ></ElImage>
                    <p>星卡官网</p>
                  </div>
                </ElDropdown>
              </div>
              <div class="other_item">
                <ElDropdown v-slots={newsSlots}>
                  <div>
                    <ElImage
                      src={`${VITE_STATIC_URL}/tcpl/p_news.png`}
                    ></ElImage>
                    <p>公司新闻</p>
                  </div>
                </ElDropdown>
              </div>
              <div class="other_item">
                <ElDropdown v-slots={dynamicSlots}>
                  <div>
                    <ElImage
                      src={`${VITE_STATIC_URL}/tcpl/p_dynamic.png`}
                    ></ElImage>
                    <p>行业动态</p>
                  </div>
                </ElDropdown>
              </div>

              <div onClick={getJournalList} class="other_item">
                <ElImage
                  src={`${VITE_STATIC_URL}/tcpl/p_journal.png`}
                ></ElImage>
                <p>电子期刊</p>
              </div>
              <div class="other_item">
                <a
                  href={`http://112.74.53.253:9527/#/index?userId=${dingdingInfo.value.ding_userid}`}
                  target="_blank"
                >
                  <ElImage
                    src={`${VITE_STATIC_URL}/tcpl/p_study.png`}
                  ></ElImage>
                  <p>星卡学院</p>
                </a>
              </div>
              <div class="other_item">
                <a href="http://192.168.29.172/PLM" target="_blank">
                  <ElImage src={`${VITE_STATIC_URL}/tcpl/p_plm.png`}></ElImage>
                  <p>PLM</p>
                </a>
              </div>
            </div>
          </div>
          <div class="right">
            <div class="sale flex-start">
              <div class="sale_item">
                <div class="num flex-center">
                  {rollText(props.userInfo.sale_data?.month_rate, 'month_rate')}
                  <HTip content="<div><p>【该数据每日凌晨更新一次】</p><p>当月营收达成率：全公司当月的实际销售收入/全公司当月的销售目标*100%</p></div>" />
                </div>
                <div class="title">当月营收达成率</div>
              </div>
              <div
                onClick={() => (monthItem.value.visible = true)}
                class="sale_item hover-color"
              >
                <div class="num flex-center">
                  {rollText(props.userInfo.organize_rate, 'organize_rate')}
                  <HTip content="<div><p>【该数据每日02:00更新一次】</p><p>组织绩效达成率由4个指标综合计算得出：产品平均合格率、生产事故、客诉降幅、退货率。</p></div>" />
                </div>
                <div class="title" style={{ transform: 'translateX(-12px)' }}>
                  组织绩效
                </div>
              </div>
              {props.userInfo.column?.includes('1') && (
                <div
                  onClick={() =>
                    viewPerformanceDetail(props.userInfo.performance_grade_id)
                  }
                  class="sale_item hover-color"
                >
                  <div class="num">
                    {props.userInfo.performance_grade || '-'}
                  </div>
                  <div class="title">上月绩效</div>
                </div>
              )}
              {props.userInfo.column?.includes('2') && (
                <div
                  onClick={() =>
                    viewPerformanceDetail(props.userInfo.score_rate_id)
                  }
                  class="sale_item hover-color"
                >
                  <div class="num flex-center">
                    {rollText(props.userInfo.score_rate, 'score_rate')}
                    <HTip content="<div><p>【该数据每日02:00更新一次】</p><p>本月绩效达成率的统计为自动计算的计算绩效指标，不包括手动评分的绩效指标数据。可点击数字查看详情。</p></div>" />
                  </div>
                  <div class="title" style={{ transform: 'translateX(-12px)' }}>
                    本月绩效
                  </div>
                </div>
              )}
              {props.userInfo.column?.includes('3') && (
                <div class="sale_item">
                  <div class="num">
                    {rollText(props.userInfo.mysale_rate, 'mysale_rate')}
                  </div>
                  <div class="title">本月业绩</div>
                </div>
              )}
            </div>
          </div>
        </div>
        <ItemTable
          ref={itemTableRef}
          id={performanceId.value}
          title={detailTitle()}
        />
        <GroupItemTable data={null} ref={groupItemTableRef} />
        <ElDialog
          lock-scroll
          draggable
          v-model={dialogVisible.value}
          title="电子期刊"
          style={{ maxWidth: '800px', with: 'auto' }}
        >
          <iframe
            width="100%"
            height="550px"
            src="https://flbook.com.cn/c/vDueBe84MH"
            frameborder="0"
          ></iframe>
          {/* <ElTable
            header-row-class-name="table_header"
            size="small"
            data={tableData.value}
          >
            <ElTableColumn prop="name" label="期刊标题" />
            <ElTableColumn
              width="45px"
              label="详情"
              v-slots={{
                default: ({ row }: AnyObject) => (
                  <a href={row.content} target="_blank" class="table_detail">
                    详情
                  </a>
                )
              }}
            ></ElTableColumn>
          </ElTable>
          <ElPagination
            v-model:current-page={pageable.value.page}
            v-model:page-size={pageable.value.pageSize}
            small
            page-sizes={[15, 30, 50, 100]}
            hide-on-single-page
            layout="total, sizes, prev, pager, next, jumper"
            total={pageable.value.total}
            onSize-change={handleSizeChange}
            onCurrent-change={handleCurrentChange}
          ></ElPagination> */}
        </ElDialog>
        <MonthItem ref={monthItem} />
      </>
    );
  }
});
